<template>
  <el-card>
    <el-col :span="4">
      <deptTree @setDeptId="setDeptId" />
    </el-col>
    <el-col :span="20">
      <div class="userTable">
        <el-form :inline="true" :model="searchParam" ref="searchRef">
          <el-form-item label="用户名称">
            <el-input
              v-model="searchParam.username"
              placeholder="请输入用户名称"
              clearable
              @keyup.enter="getTableData"
            ></el-input>
          </el-form-item>
          <el-form-item label="手机号码">
            <el-input
              placeholder="请输入手机号码"
              v-model="searchParam.phoneNumber"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item label="状态">
            <el-select
              placeholder="请选择状态"
              v-model="searchParam.status"
              @keyup.enter="getTableData"
            >
              <el-option
                v-for="(value, key, index) in userStatus"
                :key="index"
                :label="value"
                :value="key"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <commonBtn
              :value="'搜索'"
              :type="'primary'"
              :icon="'search'"
              :plain="true"
              @click="getTableData"
            ></commonBtn>
            <commonBtn
              :value="'重置'"
              :icon="'refresh'"
              @click="refreshFn"
            ></commonBtn>
          </el-form-item>
        </el-form>
        <el-row>
          <commonBtn
            :value="'新增'"
            :type="'primary'"
            :icon="'plus'"
            :plain="true"
            @click="addUserFn"
          ></commonBtn>
          <commonBtn
            :value="'删除'"
            :type="'danger'"
            :icon="'delete'"
            :plain="true"
            :disabled="ids.length === 0"
            @click="delUsertFn"
          ></commonBtn>
        </el-row>
        <el-table
          :data="searchParam.data"
          v-loading="isLoad"
          @selection-change="handleSelectionChange"
          ref="multipleTableRef"
        >
          <el-table-column type="selection" width="55" class="center" />
          <el-table-column
            label="用户编号"
            align="center"
            show-overflow-tooltip
          >
            <template #default="scope">
              {{
                (searchParam.current - 1) * searchParam.size + scope.$index + 1
              }}
            </template>
          </el-table-column>
          <el-table-column label="用户名称" prop="username"></el-table-column>
          <el-table-column label="用户昵称" prop="nickName"></el-table-column>
          <el-table-column label="部门" prop="deptName"></el-table-column>
          <el-table-column
            label="手机号码"
            prop="phoneNumber"
          ></el-table-column>
          <el-table-column label="状态">
            <template #default="scope">
              <el-tag v-if="scope.row.status == '0'">{{
                scope.row.statusDict
              }}</el-tag>
              <el-tag type="danger" v-if="scope.row.status == '1'">{{
                scope.row.statusDict
              }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column
            prop="createTime"
            label="创建时间"
            align="center"
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column label="操作" fixed="right" align="center">
            <template #default="scope">
              <editBtn
                :value="'编辑'"
                v-if="scope.row.userId != 0"
                @click="editUserFn(scope.row)"
              />
              <delBtn
                :value="'删除'"
                v-if="scope.row.userId != 0"
                @click="delUserOne(scope.row.userId)"
              />
            </template>
          </el-table-column>
        </el-table>
        <pag
          :showPage="true"
          :pageData="searchParam"
          @getTableData="getTableData"
        />
      </div>
    </el-col>
    <addEdit
      :layer="layer"
      :statusArr="userStatus"
      :deptRole="deptRole"
      @getTableData="getTableData"
      v-if="layer.show"
    />
  </el-card>
</template>
<script lang="js">
import { ref, reactive } from "vue";
import deptTree from "./deptTree.vue";
import { getUserTable, deleteUser } from "@/api/user.js";
import { queryDict } from "@/api/dictValue.js";
import commonBtn from "_c/commonBtn/index.vue";
import editBtn from "_c/editBtn/index.vue";
import delBtn from "_c/delBtn/index.vue";
import pag from "_c/pag/index.vue";
import { ElMessage, ElMessageBox } from "element-plus";
import addEdit from "./addEdit.vue";
import {queryAllDept} from '@/api/dept.js'
import { findAllRole } from '@/api/role.js'
import { findAllPost } from '@/api/post.js'
export default {
  components: {
    deptTree,
    commonBtn,
    editBtn,
    delBtn,
    pag,
    addEdit,
  },
  setup() {
    //部门、角色数据、岗位数据
    const deptRole = reactive({
      roles: [],
      depts: [],
      posts: []
    });
    // 弹窗控制器
    const layer = reactive({
      show: false,
      title: "新增",
      showButton: true,
      width: 600,
    });
    //表格引用
    const multipleTableRef = ref(null);
    //表格加载
    const isLoad = ref(true);
    //需要删除的数据
    const ids = ref([]);
    //搜索条件
    const searchParam = reactive({
      deptId: "",
      username: "",
      phoneNumber: "",
      status: "",
      current: 1,
      size: 10,
      total: 0,
      data: [],
    });

    //查询
    const getTableData = async () => {
      let params = {
        pageNum: searchParam.current,
        pageSize: searchParam.size,
        deptId: searchParam.deptId || undefined,
        username: searchParam.username || undefined,
        phoneNumber: searchParam.phoneNumber || undefined,
        status: searchParam.status || undefined,
      };
      const { data, success } = await getUserTable(params);
      if (success) {
        searchParam.data = data.records;
        searchParam.total = parseInt(data.total);
        isLoad.value = false;
      }
    };
    getTableData();

    //表单引用
    const searchRef = ref(null);
    //用户状态
    const userStatus = ref({});
    //获取用户状态
    const getUserStatus = async () => {
      const { data, success } = await queryDict("user_status");
      if (success) {
        userStatus.value = data;
      }
    };
    //用于设置部门id
    const setDeptId = (deptId) => {
      if (deptId) {
        searchParam.deptId = deptId;
        getTableData();
      }
    };

    getUserStatus();
    //多选操作
    const handleSelectionChange = (val) => {
      ids.value = [];
      if (val) {
        if (val.length > 0) {
          for (let i = 0; i < val.length; i++) {
            ids.value.push(val[i]["userId"]);
          }
        }
      }
    };
    //删除方法
    const delUser = async () => {
      const { success } = await deleteUser({ ids: ids.value });
      if (success) {
        ids.value = [];
        getTableData();
        ElMessage.success("操作成功！");
      }
    };
    //批量删除操作
    const delUsertFn = () => {
      if (ids.value.length === 0) {
        return;
      }
      ElMessageBox.confirm("您确认要删除吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          delUser();
        })
        .catch(() => {
          multipleTableRef.value.clearSelection();
        });
    };
    //删除单个
    const delUserOne = (id) => {
      ids.value = [];
      if (id) {
        ids.value.push(id);
        ElMessageBox.confirm("您确认要删除吗？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            delUser();
          })
          .catch(() => {
            ids.value = [];
            ElMessage.info("取消成功！");
          });
      }
    };
    //新增岗位弹框
    const addUserFn = () => {
      layer.title = "添加用户";
      layer.show = true;
      delete layer.row;
    };
    //编辑用户
    const editUserFn = (row) =>{
      layer.title="编辑用户";
      layer.show=true;
      layer.row=row;
    }
    //重置搜索条件
    const refreshFn = () => {
      searchParam.username = "";
      searchParam.phoneNumber = "";
      searchParam.status = "";
      getTableData();
    };
    //用于查询所有部门和角色
    const queryDeptAndRole = async () =>{
      //查询岗位
      const {data,success} = await queryAllDept();
      if(success) {
        deptRole.depts=data;
      }
      //查询角色
      const result = await findAllRole();
      if(result.success){
        deptRole.roles=result.data;
      }

      //查询岗位
      const resp  = await findAllPost();
      if(resp.success) {
        deptRole.posts=resp.data;
      }
    };
    queryDeptAndRole();
    return {
      deptRole,
      layer,
      ids,
      isLoad,
      searchParam,
      searchRef,
      userStatus,
      multipleTableRef,
      getTableData,
      setDeptId,
      handleSelectionChange,
      delUsertFn,
      delUserOne,
      addUserFn,
      refreshFn,
      editUserFn
    };
  },
};
</script>
<style lang="scss" scoped>
.el-card {
  width: 100%;
  height: 100%;
  box-sizing: border-box;
}
.el-form {
  display: flex;
  justify-content: left;
}
.userTable {
  margin-left: 20px;
  width: 100%;
}
.el-table {
  margin-top: 15px;
}
</style>
